define(['jquery', "controller","rights","bootstrap","validate","select2"], function ($) {

    var c = require("controller");
    var rights=require("rights");

    var tHeight = $(window).height() - 50 - 35;
    $(".content").height(tHeight);

    return {
        init: function () {
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow:null,
        searchData:{},
        initDataTable: function () {
            var self = this;
            this.dataTable = c.myDataTable($(".customer-table"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length
                    };
                    $.extend(true,param,self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "customer/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {

                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.customers;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);

                        }
                    });
                },
                scrollY: (tHeight - 210) + "px",
                scrollCollapse: true,
                columns: [
                    {"data": "role"},
                    {"data": "name"},
                    {"data": "username"},
                    {"data": "cid"}
                ],
                columnDefs: [
                    {
                        "targets": 0,//角色列
                        "data": null,
                        "render": function (data, type, row) {
                            switch (row.role) {
                                case 'CORP':
                                    return '通航公司';
                                case 'CAAC':
                                    return '民航领导';
                                case 'ARMY':
                                    return '军队领导';
                                case 'ADMIN':
                                    return '管理员';
                            }
                        }
                    },
                    {
                        "targets": 3,//所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 4,//操作按钮目标列
                        "data": null,
                        "render": function (data, type, row) {
                            var html = "<div>" +
                                "<a href='#' class='btn btn-sm btn-info margin-r-5' data-toggle='modal' data-target='#myModal' data-rights='9004'><i class='fa fa-edit'></i>编辑</a>" +
                                "<a href='#' class='btn btn-sm btn-danger' data-rights='9005'><i class='fa fa-remove'></i>删除</a>" +
                                "</div>";
                            return html;
                        }
                    }],
                drawCallback: function(settings, json) {
                    rights.isShowFn($('.content'));
                }
            });
        },
        bindEvent: function () {
            var self = this;
            $('#addUser').on('click', function () {
                //添加
                $("#myModal>.modal-dialog").load("customer/form.html", function(){
                    self.formInit()
                });
            });
            $('.customer-table').on('click', '.btn-info', function () {
                    //编辑
                    var dataRow = self.dataTable.row( $(this).parents('tr') ).data();
                    $("#myModal>.modal-dialog").load("customer/form.html", function(){
                        self.formInit(dataRow)
                    });
                })
                .on('click', '.btn-danger', function () {
                    //删除
                    var dataRow = self.dataTable.row($(this).parents('tr')).data();
                    c.confirm({
                        content:"是否删除",
                        confirm: function(){

                            c.ajax({

                                    url: "customer/delete",
                                    data: {
                                        id: dataRow.id
                                    },
                                    type:'POST',
                                    //headers:{"Access-Control-Allow-Origin":"*"},
                                    success: function (res) {
                                        if (res.err < 0) {
                                            alert(res.msg);
                                            return
                                        }
                                        self.dataTable.ajax.reload();
                                        /*self.dataTable.row($('.J_remove'))
                                         .remove().draw();*/
                                    }
                                }
                            )
                        }
                    })

                })
                .on('click', 'tr', function () {
                    $(this).siblings().removeClass("select");
                    $(this).toggleClass("select");

                });
            $('#search').on('click',function () {
                self.searchData={};
                if($('#searchUserName').val()!=""){
                    self.searchData.username=$('#searchUserName').val();
                }
                if($('#searchName').val()!=""){
                    self.searchData.name=$('#searchName').val();
                }
                self.dataTable.draw();
            });

            $('[name="role"]').on('change', function () {
                if ($('[name="role"]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
            });

        },
        formInit:function (dataRow) {
            var self=this;
            var $form = $('.cus-edit-form');
            $form.data("rights","");
            var Companys=c.getAllCompanys();
            $.each(Companys,function (i,v) {
                $('[name="cid"]',$form).append('<option value="'+v.cid+'">'+v.name+'</option>');
            });
            self.isCreate=true;
            $('[name="cid"],[name="role"]',$form).select2();
            if(dataRow){//判断是否编辑
                self.isCreate=false;
                $form.find('[name="role"]').val(dataRow.role).trigger('change');
                $form.find('[name="role_name"]').val(dataRow.name);
                $form.find('[name="username"]').val(dataRow.username);
                $form.find('[name="pass"]').val(dataRow.pass);
                $form.find('[name="confirm_password"]').val(dataRow.pass);
                $form.find('[name="cid"]').val(dataRow.cid).trigger('change');
                $form.find('[name="id"]').val(dataRow.id);
                $form.data("rights",dataRow.rights);
                $('#myModal').find('.modal-title').text('编辑用户');

                if ($('[name=role]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
                isCreate=false
            }
            isShowCompany();
            $('[name="role"]').change(function () {
                isShowCompany()
            });

            function isShowCompany() {
                if($('[name="role"]').val()=="CORP"){
                    $('.company').show();
                }else{
                    $('.company').hide();
                }
            }

            $('#customerForm').validate({
                rules:{
                    pass:{
                        minlength: 6
                    },
                    confirm_password: {
                        required: true,
                        minlength: 6,
                        equalTo: "#pass"
                    }
                },
                ignore:".ignore",
                messages: {
                    pass:{
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个字母"
                    },
                    confirm_password: {
                        required: "请输入密码",
                        minlength: "密码长度不能小于 6 个字母",
                        equalTo: "两次密码输入不一致"
                    }
                },
                submitHandler:function(form){
                    var mode = $('#myModal').find('.modal-title').text();
                    var formData = new FormData($('.cus-edit-form').get(0));

                    var params = {
                        role: formData.get('role'),
                        name: formData.get('role_name'),
                        username: formData.get('username'),
                        pass: formData.get('pass'),
                        rights: $form.data("rights"),//暂时
                        id: formData.get('id')
                    };

                    if (params.role === 'CORP') {
                        params['cid'] = formData.get('cid')
                    }

                    var url='customer/';
                    if (mode === "创建用户") {
                        url+= 'create';

                    } else {
                        url+= 'update';
                    }
                    c.ajax({
                        url: url,
                        dataType: "json",
                        cache: false,
                        data: params,
                        success: function (res) {
                            $('#myModal').modal('hide');
                            if (res.err < 0) {
                                return;
                            }
                            self.dataTable.ajax.reload();
                        }
                    });
                }
            });



            $('#openRights').on('click', function () {
                //自定义权限
                $("#rightsModal>.modal-dialog").load("customer/formrights.html", function(){
                    self.formRightsInit($form.find('[name="role"]').val(),$form)
                });
            });
        },
        isCreate:true,
        formRightsInit:function (role,$form) {
            var self=this;
            c.ajax({
                url: 'rights',
                dataType: "json",
                cache: false,
                data: {
                    role:role
                    // action:
                },
                success: function (res) {
                    var target=$('#rightsModleContent');
                    var oldRights=$form.data('rights');
                    $.each(res,function (key,value) {
                        var checkbox = document.createElement('input');
                        checkbox.type="checkbox";
                        checkbox.value = key;
                        if((oldRights.indexOf(key*1)>=0 || oldRights.indexOf(key)>=0)||self.isCreate){
                            checkbox.checked = true;
                        }

                        if(key/100==Math.floor(key/100) && key*1 > 200){
                            target.append('<p style="border: 1px dashed #ccc;margin-bottom: 5px;"></p>');
                        }
                        var div = $('<div class="checkbox-div"></div>').css({'width':'20%','display':'inline-block','padding-left':'15px'}).append(checkbox).append('<label onclick="$(this).prev().click()">'+value+'</label>');
                        target.append(div);
                    });
                }
            });
            $("#rightsModleButton").on('click', function () {
                var data=[];
                $.each($('input:checked',$('#rightsModleContent')),function () {
                    data.push($(this).val())
                });
                $form.data("rights",data.join(','));
                $('#rightsModal').modal('hide');
                self.isCreate=false;

            });

            $('#rightsModleContent').on('click','input',function (e) {

                if(!$(this).is(':checked')) {
                    // do something
                    var _this=this;
                    var val=$(_this).val();
                    switch (val){
                        case "500":
                            isCheck("100","航路监视");
                            isCheck("501","飞行要素操作");
                            isCheck("502","飞行要素审批");
                            break;
                        case "600":
                            isCheck("601","飞行器操作");
                            break;
                        case "800":
                            isCheck("801","飞行员操作");
                            break;
                        case "400":
                            isCheck("301","飞行计划操作");
                            break;
                        case "300":
                            isCheck("301","飞行计划操作");
                            isCheck("302","飞行计划审批");
                            isCheck("310","批次检索");
                            isCheck("311","批次操作");
                            break;
                        case "310":
                            isCheck("311","批次操作");
                            break;

                    }

                }
                
                
                function isCheck(v,text) {
                    if($('input[value="'+v+'"]').is(':checked')){
                        c.confirm({
                            content: '取消该权限会导致['+text+']不能正常使用，是否取消？',
                            cancel: function(){
                                $(_this).prop('checked','checked');
                            }
                        });
                    }
                }
            })



        }
    }
});



